package cvi.com.reader.activity;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.lsjwzh.widget.recyclerviewpager.RecyclerViewPager;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnDismissListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.orhanobut.hawk.Hawk;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import cvi.com.reader.R;
import cvi.com.reader.adapter.PictureBookWorksAdapter;
import cvi.com.reader.adapter.ReportGridViewAdapter;
import cvi.com.reader.base.BaseActivity;
import cvi.com.reader.bean.ChartDataBean;
import cvi.com.reader.bean.ReportBean;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.DateUtil;
import cvi.com.reader.widgets.MyGridView;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 梅涛 on 2020/8/4.
 * <p>
 * 排行榜绘本试听界面
 */

public class  PictureBookAuditionActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.tittle)
    TextView tittle;
    @BindView(R.id.right_icon)
    LinearLayout rightIcon;
    @BindView(R.id.bb)
    View bb;
    @BindView(R.id.imageview)
    CircleImageView imageview;
    @BindView(R.id.reader)
    TextView reader;
    @BindView(R.id.score)
    TextView score;
    @BindView(R.id.ima_praise)
    LinearLayout imaPraise;
    @BindView(R.id.report_ll)
    LinearLayout reportLl;
    @BindView(R.id.dd)
    View dd;
    @BindView(R.id.progressBar)
    SeekBar progressBar;
    @BindView(R.id.current_time)
    TextView currentTime;
    @BindView(R.id.all_time)
    TextView allTime;
    @BindView(R.id.play)
    Button play;
    @BindView(R.id.praise_num)
    TextView praiseNum;
    @BindView(R.id.gg)
    RelativeLayout gg;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.report_tv)
    TextView reportTv;
    @BindView(R.id.viewpager)
    RecyclerViewPager mRecyclerView;
    private ChartDataBean.DataBean dataBean = null;
    private int record_id = -1;
    public DialogPlus reportDialog;
    private List<ReportBean.DataBean> dataBeanList = new ArrayList<>();
    private ReportGridViewAdapter reportGridViewAdapter = null;
    private MyGridView myGridView;
    private boolean isPraise = false;
    private int praiseNumb;
    private int reportReanson = -1;
    private boolean isReport = false;
    private MediaPlayer mediaPlayer = new MediaPlayer();//实例化MediaPlayer类
    private String strUrl = null;
    private Timer timer = new Timer();
    private int iniTime = 0;
    private int duration;
    private int progressValue = 0;
    private boolean isPause = false;
    private TimerTaskChildren taskChildren;
    private boolean isFinish = false;//是否播放完了
    private List<String> strings = new ArrayList<>();
    private String musicUrl;
    private String Tag = "PictureBookAuditionActivityyyyyyy";
    /**
     * 线程处理Handler
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case constant.HANDLER_MESSAGE_WHAT_PLAY_TIME:
                    if (mediaPlayer != null) {
                        currentTime.setText(DateUtil.toVideoTime(mediaPlayer.getCurrentPosition()));
                        progressBar.setProgress(mediaPlayer.getCurrentPosition() / 1000);

                    }
                    Log.d(Tag, "  duration=" + duration + "   mediaPlayer.getCurrentPosition()=" + Math.round(Double.valueOf(String.valueOf(mediaPlayer.getCurrentPosition())) / 1000) + "  进度条秒数" + progressBar.getProgress() / 1000 + "  进度" + mediaPlayer.getCurrentPosition());
                    if (duration == mediaPlayer.getCurrentPosition()) {

                    }
                    break;
            }
        }
    };
    private PictureBookWorksAdapter pictureBookWorksAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pivture_book_audition;
    }

    @Override
    protected void initView() {
        back.setOnClickListener(this);
        imaPraise.setOnClickListener(this);
        reportLl.setOnClickListener(this);
        play.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        if (Hawk.contains("ChartDataBean")) {
            dataBean = Hawk.get("ChartDataBean");
        }
        if (dataBean != null) {
            ChartDataBean.DataBean.UserBean userBean = dataBean.getUser();
            ChartDataBean.DataBean.MaterialBean materialBean = dataBean.getMaterial();
            reader.setText("朗读者：" + userBean.getRealname());
            score.setText("得分：" + dataBean.getScore() + "");
            //     content.setText(Html.fromHtml(materialBean.getContent()) + "<p><span >携着春风之情思，夏雨之气势，秋叶之精神，冬，又来了。<\\/span><span ><br><\\/span><span >冬赋予它们以自己的品性，于是，风凛冽了，雪飘舞了，土地冰冻了<\\/span><\\/p><p><span >水瘦山寒，天高地远，大自然一片清雅素淡<\\/span><span >;<\\/span><span ><br><\\/span><span >刚劲的寒风好像一把大扫帚，把那些作恶多端的蝇蚊毒虫一扫而光，把那些孳生罪恶的稗草毒藤处以极刑；浊水缩小了身体，垃圾收敛了恶臭；<\\/span><span ><br><\\/span><span >接着，那翩然而至的大大小小的雪花，又把大地银装素裹，装扮得一片莹白；<\\/span><span ><br><\\/span><span >不下雪时，那渺茫茫的天空悬挂着清凛凛的高远，空旷旷的大地袒露着黄澄澄的真诚。<\\/span><\\/p>");
            praiseNum.setText(dataBean.getLikes() + "人已点赞");
            praiseNumb = dataBean.getLikes();
            tittle.setText("《" + materialBean.getMaterial_name() + "》" + "-" + materialBean.getAuthor());
            record_id = dataBean.getId();
            if (0 == dataBean.getLikes_clicked()) {
                image.setBackgroundResource(R.mipmap.ic_unpraise);
                isPraise = false;
            } else {
                image.setBackgroundResource(R.mipmap.ic_praise);
                isPraise = true;
            }
            if (1 == dataBean.getTipoff()) {
                reportTv.setText("已举报");
            } else {
                reportTv.setText("举报");
            }
      /*      if (Hawk.contains("ip")) {
                strUrl = Hawk.get("ip");
            }
            if (strUrl != null) {

            }*/
            Glide.with(PictureBookAuditionActivity.this).load("http://" + constant.URL  + userBean.getAvatar()).into(imageview);
            musicUrl = "http://" + constant.URL  + dataBean.getMedia_path();
            initPlayer(musicUrl);

            Log.d("dfsffaf", materialBean.getMedia_path());
            String[] str = null;
            if (materialBean.getMedia_path().contains(",")) {
                str = materialBean.getMedia_path().split(",");
                Log.d("dfsffaf4444", materialBean.getMedia_path());
            } else if (materialBean.getMedia_path().contains("，")) {
                Log.d("dfsffaf555", materialBean.getMedia_path());
                str = materialBean.getMedia_path().split("，");
            }

            if (str != null) {
                for (int i = 0; i < str.length; i++) {
                    strings.add(str[i]);

                }
            }
            Log.d("dfsffaf222", strings.size() + "");
            initViewPager();
        }
//获取举报数据
        getReportData();
    }

    private void initPlayer(String musicUrl) {
        Uri uri = Uri.parse(musicUrl);//网络中的音乐文件
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(this, uri);//音乐文件路径
            mediaPlayer.prepare();//资源文件准备
        } catch (IOException e) {
            e.printStackTrace();
        }
        duration = mediaPlayer.getDuration();//获取音频的时间
        String timelong = duration / 1000 + "s";
        progressBar.setMax(duration / 1000);
        allTime.setText(DateUtil.toVideoTime(duration));
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                Log.d(Tag + "1", "  总时间duration=" + mediaPlayer.getDuration() + "  最终进度" + mediaPlayer.getCurrentPosition() +
                        "  最终秒数" + mediaPlayer.getCurrentPosition() / 1000 + "   进度条=" + progressBar.getProgress() + "  进度条秒数" + progressBar.getProgress() / 1000);
                //  currentTime.setText(DateUtil.toVideoTime(mediaPlayer.getDuration()));
                currentTime.setText("00:00");
                progressBar.setProgress(0);
                play.setBackgroundResource(R.mipmap.ic_auditon_play);
                isFinish = true;
                if (taskChildren != null) {
                    taskChildren.cancel();
                }


            }
        });
    }

    //播放器播放
    public void onPlayerClick(String url) {
      /*  Log.d("dsffff", "222223333" + url);
        Uri uri = Uri.parse(url);//网络中的音乐文件
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(this, uri);//音乐文件路径
            mediaPlayer.prepare();//资源文件准备
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        if (isFinish) {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.seekTo(0);
            }
          /*  Uri uri = Uri.parse(musicUrl);//网络中的音乐文件
            try {
               // mediaPlayer.reset();
                mediaPlayer.setDataSource(this, uri);//音乐文件路径
                mediaPlayer.prepare();//资源文件准备
            } catch (IOException e) {
                e.printStackTrace();
            }
            duration = mediaPlayer.getDuration();//获取音频的时间
            String timelong = duration / 1000 + "s";
            progressBar.setMax(duration / 1000);*/
            isFinish = false;
            //  taskChildren.cancel();
        }
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();//播放
        }
        //  mediaPlayer.start();//播放
        taskChildren = new TimerTaskChildren();
        timer.schedule(taskChildren, 0, 1000);
        // musicListAdapter.notifyDataSetChanged();
    }

    //播放器暂停
    public void onPauseClick() {
        Log.d(Tag, "11111122222" + musicUrl);
        if (duration / 1000 > Math.round(Double.valueOf(String.valueOf(mediaPlayer.getCurrentPosition())) / 1000)) {
            isPause = true;
            if (taskChildren != null) {
                taskChildren.cancel();
            }

        }
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();//暂停
        }
        // musicListAdapter.notifyDataSetChanged();
    }


    @Override
    protected void extrasDoSome(Bundle extras) {

    }

    protected void initViewPager() {
        Log.d("dfsffaf11", strings.size() + "");
        LinearLayoutManager layout = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,
                false);
        mRecyclerView.setLayoutManager(layout);
        pictureBookWorksAdapter = new PictureBookWorksAdapter(PictureBookAuditionActivity.this, strings);
        mRecyclerView.setAdapter(pictureBookWorksAdapter);
        pictureBookWorksAdapter.notifyDataSetChanged();
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLongClickable(true);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int scrollState) {
//                updateState(scrollState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int i, int i2) {
//                mPositionText.setText("First: " + mRecyclerViewPager.getFirstVisiblePosition());
                int childCount = mRecyclerView.getChildCount();
                int width = mRecyclerView.getChildAt(0).getWidth();
                int padding = (mRecyclerView.getWidth() - width) / 2;
//                mCountText.setText("Count: " + childCount);

                for (int j = 0; j < childCount; j++) {
                    View v = recyclerView.getChildAt(j);
                    //往左 从 padding 到 -(v.getWidth()-padding) 的过程中，由大到小
                    float rate = 0;
                    ;
                    if (v.getLeft() <= padding) {
                        if (v.getLeft() >= padding - v.getWidth()) {
                            rate = (padding - v.getLeft()) * 1f / v.getWidth();
                        } else {
                            rate = 1;
                        }
                        v.setScaleY(1 - rate * 0.1f);
                        v.setScaleX(1 - rate * 0.1f);

                    } else {
                        //往右 从 padding 到 recyclerView.getWidth()-padding 的过程中，由大到小
                        if (v.getLeft() <= recyclerView.getWidth() - padding) {
                            rate = (recyclerView.getWidth() - padding - v.getLeft()) * 1f / v.getWidth();
                        }
                        v.setScaleY(0.9f + rate * 0.1f);
                        v.setScaleX(0.9f + rate * 0.1f);
                    }
                }
            }
        });
        mRecyclerView.addOnPageChangedListener(new RecyclerViewPager.OnPageChangedListener() {
            @Override
            public void OnPageChanged(int oldPosition, int newPosition) {
                Log.d("test", "oldPosition:" + oldPosition + " newPosition:" + newPosition);
            }
        });

        mRecyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (mRecyclerView.getChildCount() < 3) {
                    if (mRecyclerView.getChildAt(1) != null) {
                        if (mRecyclerView.getCurrentPosition() == 0) {
                            View v1 = mRecyclerView.getChildAt(1);
                            v1.setScaleY(0.9f);
                            v1.setScaleX(0.9f);
                        } else {
                            View v1 = mRecyclerView.getChildAt(0);
                            v1.setScaleY(0.9f);
                            v1.setScaleX(0.9f);
                        }
                    }
                } else {
                    if (mRecyclerView.getChildAt(0) != null) {
                        View v0 = mRecyclerView.getChildAt(0);
                        v0.setScaleY(0.9f);
                        v0.setScaleX(0.9f);
                    }
                    if (mRecyclerView.getChildAt(2) != null) {
                        View v2 = mRecyclerView.getChildAt(2);
                        v2.setScaleY(0.9f);
                        v2.setScaleX(0.9f);
                    }
                }

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.ima_praise:
                if (dataBean != null) {
                    if (isPraise) {
                        cancelPraise(record_id);
                        isPraise = false;
                    } else {
                        setPraise(record_id);
                        isPraise = true;
                    }
                }

                break;
            case R.id.report_ll:
                if (dataBean != null) {
                    if (1 == dataBean.getTipoff() || isReport) {
                        reportTv.setText("已举报");
                        Toast.makeText(PictureBookAuditionActivity.this, "您已举报过了！", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                showDialog();
                break;
            case R.id.play:
                if (mediaPlayer.isPlaying()) {//暂停播放
                    onPauseClick();
                    //mediaPlayer.pause();
                    play.setBackgroundResource(R.mipmap.ic_auditon_play);
                } else {//开始播放
                    onPlayerClick(musicUrl);

                }
                break;
        }

    }


    private void setPraise(int record_id) {
        //绑定生命周期
        NetWorkManager.getInstance().getNetWorkApiService().setPraise(record_id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PictureBookAuditionActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        Toast.makeText(PictureBookAuditionActivity.this, "点赞成功！", Toast.LENGTH_LONG).show();
                        image.setBackgroundResource(R.mipmap.ic_praise);
                        if (dataBean != null) {
                            praiseNumb = praiseNumb + 1;
                            Log.d("efweffwf", praiseNumb + "");
                            praiseNum.setText(praiseNumb + "人已点赞");
                        }

                    }
                });
    }

    //取消点赞
    private void cancelPraise(int record_id) {
        //绑定生命周期
        NetWorkManager.getInstance().getNetWorkApiService().canclePraise(record_id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PictureBookAuditionActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        Toast.makeText(PictureBookAuditionActivity.this, "取消成功！", Toast.LENGTH_LONG).show();
                        image.setBackgroundResource(R.mipmap.ic_unpraise);
                        if (dataBean != null) {
                            praiseNumb = praiseNumb - 1;
                            Log.d("efweffwf", praiseNumb + "");
                            praiseNum.setText(praiseNumb + "人已点赞");
                        }

                    }
                });
    }

    private void showDialog() {
        View view = LayoutInflater.from(PictureBookAuditionActivity.this).inflate(R.layout.report_radio_button, null);
        Button reportBtn = view.findViewById(R.id.report_btn);
        myGridView = view.findViewById(R.id.mylistview);
        LinearLayout close_ll = view.findViewById(R.id.close_ll);
        reportDialog = DialogPlus.newDialog(PictureBookAuditionActivity.this)
                .setContentHolder(new ViewHolder(view))
                .setCancelable(true)
                .setGravity(Gravity.CENTER)
                .setOnDismissListener(new OnDismissListener() {
                    @Override
                    public void onDismiss(DialogPlus dialog) {

                    }
                }).create();
        reportGridViewAdapter = new ReportGridViewAdapter(PictureBookAuditionActivity.this, dataBeanList);
        if (myGridView != null) {
            myGridView.setAdapter(reportGridViewAdapter);
            reportGridViewAdapter.notifyDataSetChanged();
        }
        reportDialog.show();
        myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ReportBean.DataBean dataBean = (ReportBean.DataBean) adapterView.getAdapter().getItem(i);
                reportGridViewAdapter.setSeclection(i);//传值更新i
                reportGridViewAdapter.notifyDataSetChanged();
                reportReanson = dataBean.getId();
            }
        });
        close_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reportDialog.dismiss();
            }
        });
        reportBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (-1 == reportReanson) {
                    Toast.makeText(PictureBookAuditionActivity.this, "请选择举报原因！", Toast.LENGTH_LONG).show();
                    return;
                }
                setReportData(record_id, reportReanson);
                reportDialog.dismiss();
            }
        });
    }

    private void getReportData() {
        //绑定生命周期
        NetWorkManager.getInstance().getNetWorkApiService().getReportData().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PictureBookAuditionActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        showData(response);
                    }
                });
    }

    private void showData(JSONObject response) {
        JSONArray array = response.getJSONArray("data");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            ReportBean.DataBean dataBean = (ReportBean.DataBean) JSONObject.toJavaObject(object, ReportBean.DataBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            dataBeanList.add(dataBean);
        }

    }

    //举报
    private void setReportData(int record_id, int reason_id) {
        //绑定生命周期
        NetWorkManager.getInstance().getNetWorkApiService().setReport(record_id, reason_id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(PictureBookAuditionActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        Toast.makeText(PictureBookAuditionActivity.this, "举报成功！", Toast.LENGTH_LONG).show();
                        reportTv.setText("已举报");
                        isReport = true;
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        mHandler.removeMessages(constant.HANDLER_MESSAGE_WHAT_PLAY_TIME);
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    class TimerTaskChildren extends TimerTask {
        public void run() {

            //  mHandler.sendEmptyMessage(constant.HANDLER_MESSAGE_WHAT_PLAY_TIME);
            if (duration / 1000 > Math.round(Double.valueOf(String.valueOf(mediaPlayer.getCurrentPosition())) / 1000)) {
                mHandler.sendEmptyMessage(constant.HANDLER_MESSAGE_WHAT_PLAY_TIME);
                if (mediaPlayer != null) {
                    Log.d(Tag, "  音频总时长duration=" + duration + "   progressValue=" + progressBar.getProgress() + "  播放最终进度" + mediaPlayer.getCurrentPosition());
                    Log.d(Tag, mediaPlayer.isPlaying() + "~~~");
                    /*if (mediaPlayer.isPlaying()) {
                        mHandler.sendEmptyMessage(constant.HANDLER_MESSAGE_WHAT_PLAY_TIME);
                    }*/
                }

            }/* else {
                mediaPlayer.stop();
                play.setBackgroundResource(R.mipmap.ic_auditon_play);
                progressBar.setProgress(0);
            }*/
        }
    }
}
